package com.ld.common;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ld.common.config.web.LdGlobal;
import com.ld.common.model.json.ApiResult;
import com.ld.shieldsb.common.core.reflect.ClassUtil;
import com.ld.shieldsb.common.web.util.Web;
import com.ld.shieldsb.common.web.util.WebUtil;

import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@Controller
@Slf4j
public class MainErrorController implements ErrorController {
    @Autowired
    public HttpServletRequest request;
    @Autowired
    public HttpServletResponse response;

    private static final String ERROR_PATH = "error";

    // 定义ajax 的全局错误数据返回
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public Object handleError() {
        Enumeration<String> attrNames = request.getAttributeNames();
//        javax.servlet.forward.request_uri = /software-center/a/system/bizlog
//        javax.servlet.forward.context_path = /software-center
//        javax.servlet.forward.servlet_path = /a/system/bizlog
//        javax.servlet.forward.query_string = r=1545645118621
//        javax.servlet.error.status_code = 404
        while (attrNames.hasMoreElements()) {
            String name = (String) attrNames.nextElement();
            log.debug(name + " = " + request.getAttribute(name));
        }

        // 获取statusCode:401,404,500
        String uri = (String) request.getAttribute("javax.servlet.forward.servlet_path");
        int code = ClassUtil.obj2int(request.getAttribute("javax.servlet.error.status_code"));
        String message = (String) request.getAttribute("javax.servlet.error.message");
        String admin = LdGlobal.PROJECT_ADMIN_S;
        if (admin != null) {
            admin = (admin + "/").replaceAll("\\/+", "/");
        }
        String ip = WebUtil.getIpAddr(request);
        String msg = "访问出错！";
        if (404 == code) {
            msg = "路径不存在！";
        } else if (403 == code) {
            msg = "无操作权限！" + (message != null ? message : "") + " ";
        } else if (500 == code) {
            msg = "服务器内部错误！";
        }
        if (uri != null && uri.startsWith(admin)) { // 后台
            request.setAttribute("path", uri);
            request.setAttribute("message", "没有访问权限");
            request.setAttribute("status", 401);
            request.setAttribute("error", "IP：" + ip);
            return Web.Response.error(msg + uri);
        }
        return new ApiResult<Object>(false, 500, msg + "（" + code + "）请检查:" + uri); // 前台api
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}